import { NextRequest, NextResponse } from 'next/server'
import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

// 处理单个批次的单元格
async function processCellBatch(sheetId: string, cells: any[]) {
  return await prisma.$transaction(async (tx) => {
    // 1. 先查询现有的单元格
    const existingCells = await tx.cell.findMany({
      where: {
        sheetId,
        OR: cells.map(cell => ({
          row: cell.row,
          column: cell.column
        }))
      }
    })

    // 2. 创建现有单元格的映射
    const existingMap = new Map()
    existingCells.forEach(cell => {
      existingMap.set(`${cell.row}-${cell.column}`, cell)
    })

    // 3. 分离需要更新和创建的单元格
    const cellsToUpdate: Array<{ where: { id: string }, data: { value: string | null, formula: string | null, style: any } }> = []
    const cellsToCreate: Array<{ sheetId: string, row: number, column: number, value: string | null, formula: string | null, style: any }> = []

    cells.forEach(cell => {
      const { row, column, value, formula, style } = cell
      const key = `${row}-${column}`
      
      if (existingMap.has(key)) {
        cellsToUpdate.push({
          where: { id: existingMap.get(key).id },
          data: { value, formula, style: style as any }
        })
      } else {
        cellsToCreate.push({
          sheetId,
          row,
          column,
          value,
          formula,
          style: style as any
        })
      }
    })

    // 4. 批量更新现有单元格
    const updatePromises = cellsToUpdate.map(updateData => 
      tx.cell.update(updateData)
    )

    // 5. 批量创建新单元格
    const createPromise = cellsToCreate.length > 0 
      ? tx.cell.createMany({ data: cellsToCreate })
      : Promise.resolve({ count: 0 })

    // 6. 并行执行更新和创建操作
    const [updatedCells, createResult] = await Promise.all([
      Promise.all(updatePromises),
      createPromise
    ])

    // 7. 如果需要返回创建的单元格，再次查询
    let createdCells: any[] = []
    if (cellsToCreate.length > 0) {
      createdCells = await tx.cell.findMany({
        where: {
          sheetId,
          OR: cellsToCreate.map(cell => ({
            row: cell.row,
            column: cell.column
          }))
        }
      })
    }

    return [...updatedCells, ...createdCells]
  }, {
    timeout: 15000 // 15 seconds timeout for each batch
  })
}

// 批量更新或创建单元格 - 优化版本
export async function PUT(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const sheetId = params.id
    const body = await request.json()
    const { cells } = body

    if (!Array.isArray(cells)) {
      return NextResponse.json({ error: 'Cells must be an array' }, { status: 400 })
    }

    if (cells.length === 0) {
      return NextResponse.json({ cells: [] })
    }

    // 如果数据量过大，分批处理
    const BATCH_SIZE = 1000 // 每批处理1000个单元格
    if (cells.length > BATCH_SIZE) {
      console.log(`Processing large dataset: ${cells.length} cells in batches of ${BATCH_SIZE}`)
      
      const allResults = []
      const totalBatches = Math.ceil(cells.length / BATCH_SIZE)
      
      for (let i = 0; i < cells.length; i += BATCH_SIZE) {
        const batch = cells.slice(i, i + BATCH_SIZE)
        const batchNumber = Math.floor(i / BATCH_SIZE) + 1
        
        console.log(`Processing batch ${batchNumber}/${totalBatches} (${batch.length} cells)`)
        
        try {
          const batchResults = await processCellBatch(sheetId, batch)
          allResults.push(...batchResults)
          console.log(`Batch ${batchNumber} completed successfully`)
        } catch (error) {
          console.error(`Error processing batch ${batchNumber}:`, error)
          // 如果某个批次失败，继续处理其他批次
          // 但记录错误信息
        }
      }
      
      return NextResponse.json({ 
        cells: allResults,
        message: `Successfully processed ${cells.length} cells in ${Math.ceil(cells.length / BATCH_SIZE)} batches`
      })
    }

    // 验证数据格式
    for (const cell of cells) {
      const { row, column } = cell
      if (typeof row !== 'number' || typeof column !== 'number') {
        return NextResponse.json({ error: 'Row and column must be numbers' }, { status: 400 })
      }
    }

    // 使用优化的批量处理函数
    const results = await processCellBatch(sheetId, cells)

    return NextResponse.json({ 
      cells: results,
      message: `Successfully processed ${cells.length} cells`
    })
  } catch (error) {
    console.error('Error batch updating cells:', error)
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
  }
}
